package com.newshub.app.ui.search

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import android.widget.ProgressBar
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.newshub.app.R
import com.newshub.app.ui.adapter.NewsAdapter
import com.newshub.app.data.model.News
import com.newshub.app.ui.news.NewsDetailActivity

class SearchActivity : AppCompatActivity() {

    private lateinit var viewModel: SearchViewModel
    private lateinit var newsAdapter: NewsAdapter
    private lateinit var searchEditText: EditText
    private lateinit var clearButton: Button
    private lateinit var recyclerView: RecyclerView
    private lateinit var emptyStateTextView: TextView
    private lateinit var resultsCountTextView: TextView
    private lateinit var progressBar: ProgressBar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        
        // 初始化视图
        searchEditText = findViewById(R.id.searchEditText)
        clearButton = findViewById(R.id.clearButton)
        recyclerView = findViewById(R.id.recyclerView)
        emptyStateTextView = findViewById(R.id.emptyStateTextView)
        resultsCountTextView = findViewById(R.id.resultsCountTextView)
        progressBar = findViewById(R.id.progressBar)
        
        setupViewModel()
        setupRecyclerView()
        setupSearchBar()
        observeViewModel()
        setupClearButton()
    }
    
    private fun setupViewModel() {
        viewModel = ViewModelProvider(this)[SearchViewModel::class.java]
    }
    
    private fun setupRecyclerView() {
        newsAdapter = NewsAdapter(
            onItemClick = { news ->
                // 导航到新闻详情页面
                val intent = Intent(this, NewsDetailActivity::class.java)
                intent.putExtra("news_id", news.docid)
                startActivity(intent)
            },
            onFavoriteClick = { news ->
                viewModel.toggleFavorite(news)
            }
        )
        
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = newsAdapter
    }
    
    private fun setupSearchBar() {
        searchEditText.requestFocus()
        
        searchEditText.setOnEditorActionListener { v: View?, actionId: Int, event: KeyEvent? ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch()
                return@setOnEditorActionListener true
            }
            false
        }
        
        searchEditText.setOnKeyListener { v: View?, keyCode: Int, event: KeyEvent ->
            if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                performSearch()
                return@setOnKeyListener true
            }
            false
        }
    }
    
    private fun setupClearButton() {
        clearButton.setOnClickListener {
            searchEditText.text.clear()
            searchEditText.requestFocus()
            viewModel.clearResults()
        }
    }
    
    private fun performSearch() {
        val keyword = searchEditText.text.toString().trim()
        if (keyword.isNotEmpty()) {
            // 隐藏键盘
            searchEditText.clearFocus()
            // 执行搜索
            viewModel.searchNews(keyword)
        }
    }
    
    private fun observeViewModel() {
        viewModel.searchResults.observe(this@SearchActivity, Observer<List<News>> { results ->
            if (results != null && results.isNotEmpty()) {
                newsAdapter.submitList(results)
                emptyStateTextView.visibility = View.GONE
                recyclerView.visibility = View.VISIBLE
                resultsCountTextView.visibility = View.VISIBLE
                resultsCountTextView.text = "找到 ${results.size} 条结果"
            } else {
                emptyStateTextView.visibility = View.VISIBLE
                recyclerView.visibility = View.GONE
                resultsCountTextView.visibility = View.GONE
                emptyStateTextView.text = "未找到相关新闻"
            }
        })
        
        viewModel.isLoading.observe(this, Observer<Boolean> { isLoading ->
            progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
        })
        
        viewModel.error.observe(this, Observer<String?> { errorMessage ->
            if (errorMessage != null) {
                emptyStateTextView.visibility = View.VISIBLE
                emptyStateTextView.text = errorMessage
            }
        })
    }
}